﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;

namespace Starry.SmartAjax
{
    public abstract class BizHandler : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            var bizResult = new BizResult();
            var bizEntity = default(BizEntity);
            IBizTranscation trans = null;
            try
            {
                bizEntity = this.BizFactory.CreateBizEntity(context);
                if (bizEntity is ITransactable)
                {
                    trans = bizEntity.BeginBizTranscation();
                    bizEntity.BizTranscation = trans;
                }
                bizResult = bizEntity.Execute();
                if (trans != null)
                {
                    if (bizResult.IsSuccess)
                    {
                        trans.Commit();
                    }
                    else
                    {
                        trans.Rollback();
                    }
                }
            }
            catch
            {
                bizResult.IsSuccess = false;
                bizResult.Messages.Add("系统出错，请联系系统管理员！");
                if (trans != null)
                {
                    trans.Rollback();
                }
            }
            finally
            {
                context.Response.Write(bizResult.ToResponseString());
            }
        }

        public bool IsReusable
        {
            get { return true; }
        }

        protected abstract IBizFactory BizFactory { get; }
    }
}